package com.by.flutter_init

import android.content.Context
import android.view.View
import android.os.Bundle
import android.util.Log
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.platform.PlatformView

// 高德地图导入
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.MapView
import com.amap.api.maps.model.*
import com.amap.api.location.*
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.geocoder.*
import com.amap.api.services.poisearch.PoiSearch
import com.amap.api.services.poisearch.PoiResult
import com.amap.api.services.core.PoiItem

/**
 * 高德地图Flutter Platform View
 * 
 * 🎯 功能：
 * - 显示原生高德地图
 * - 地图点击和拖拽
 * - 位置搜索(POI)
 * - 定位功能
 * - 逆地理编码
 */
class AmapFlutterMapView(
    context: Context,
    viewId: Int,
    private val binaryMessenger: BinaryMessenger,
    args: Map<String, Any>?
) : PlatformView, MethodChannel.MethodCallHandler, 
    AMap.OnMapClickListener, AMap.OnCameraChangeListener,
    AMapLocationListener, PoiSearch.OnPoiSearchListener {

    companion object {
        private const val TAG = "AmapFlutterMapView"
        private const val CHANNEL_NAME = "com.playtruly.amap_map"
    }

    private val mapView: MapView = MapView(context)
    private var aMap: AMap? = null
    private var marker: Marker? = null
    private val methodChannel: MethodChannel
    
    // 定位相关
    private var mLocationClient: AMapLocationClient? = null
    
    // POI搜索相关
    private var poiSearch: PoiSearch? = null
    
    // 当前位置信息
    private var currentLatitude: Double = 35.0
    private var currentLongitude: Double = 105.0
    private var currentAddress: String = "正在获取位置..."

    init {
        Log.d(TAG, "🗺️ =============== AmapFlutterMapView 初始化开始 ===============")
        Log.d(TAG, "📦 viewId: $viewId")
        Log.d(TAG, "📦 args: $args")
        
        // 创建Method Channel
        methodChannel = MethodChannel(binaryMessenger, "${CHANNEL_NAME}_$viewId")
        methodChannel.setMethodCallHandler(this)
        
        // 初始化地图
        initializeMap()
        
        Log.d(TAG, "✅ AmapFlutterMapView 初始化完成")
    }

    /**
     * 初始化地图
     */
    private fun initializeMap() {
        try {
            Log.d(TAG, "🔧 开始初始化高德地图...")
            
            // 必须要先调用onCreate方法
            mapView.onCreate(Bundle())
            
            // 获取AMap实例
            aMap = mapView.map
            aMap?.let { map ->
                // 设置地图属性
                map.uiSettings.isRotateGesturesEnabled = false
                map.moveCamera(CameraUpdateFactory.zoomBy(6f))
                
                // 设置监听器
                map.setOnMapClickListener(this)
                map.setOnCameraChangeListener(this)
                
                // 设置定位按钮
                map.uiSettings.isMyLocationButtonEnabled = false  // 禁用默认定位按钮
                
                // 自定义定位样式
                setupMyLocationStyle(map)
                
                // 禁用自动定位图层，避免自动跳转到用户位置
                map.isMyLocationEnabled = false
                
                // 添加中心标记点
                setupCenterMarker(map)
                
                Log.d(TAG, "✅ 高德地图初始化成功")
            } ?: run {
                Log.e(TAG, "❌ 获取AMap实例失败")
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "💥 初始化地图异常: ${e.message}", e)
        }
    }

    /**
     * 设置定位样式
     */
    private fun setupMyLocationStyle(map: AMap) {
        try {
            val myLocationStyle = MyLocationStyle().apply {
                // 自定义精度范围的圆形边框颜色（透明）
                strokeColor(0x00000000)
                // 设置圆形边框宽度
                strokeWidth(0f)
                // 设置圆形填充颜色（透明）
                radiusFillColor(0x00000000)
            }
            
            // 设置定位样式
            map.myLocationStyle = myLocationStyle
            
            Log.d(TAG, "✅ 定位样式设置成功")
        } catch (e: Exception) {
            Log.e(TAG, "💥 设置定位样式异常: ${e.message}", e)
        }
    }

    /**
     * 设置中心标记点
     */
    private fun setupCenterMarker(map: AMap) {
        try {
            val markerOptions = MarkerOptions().apply {
                draggable(true)
                title("拖动地图移动我")
                position(LatLng(currentLatitude, currentLongitude))
            }
            
            marker = map.addMarker(markerOptions)
            
            // 监听标记拖拽
            map.setOnMarkerDragListener(object : AMap.OnMarkerDragListener {
                override fun onMarkerDragStart(marker: Marker?) {
                    Log.d(TAG, "📍 标记开始拖拽")
                }

                override fun onMarkerDrag(marker: Marker?) {
                    // 拖拽过程中可以实时更新
                }

                override fun onMarkerDragEnd(marker: Marker?) {
                    marker?.position?.let { position ->
                        Log.d(TAG, "📍 标记拖拽结束: ${position.latitude}, ${position.longitude}")
                        handleSelectedLocation(position, false) // 拖拽标记时不移动相机
                    }
                }
            })
            
            Log.d(TAG, "✅ 中心标记点设置成功")
        } catch (e: Exception) {
            Log.e(TAG, "💥 设置中心标记点异常: ${e.message}", e)
        }
    }

    /**
     * 处理选中的位置
     * @param latLng 位置坐标
     * @param moveCamera 是否移动相机到该位置，默认为true
     */
    private fun handleSelectedLocation(latLng: LatLng, moveCamera: Boolean = true) {
        try {
            currentLatitude = latLng.latitude
            currentLongitude = latLng.longitude
            
            Log.d(TAG, "📍 位置已更新: $currentLatitude, $currentLongitude (moveCamera=$moveCamera)")
            
            // 进行逆地理编码获取地址
            reverseGeocode(latLng)
            
            // 通知Flutter端位置变化
            val locationData = mapOf(
                "latitude" to currentLatitude,
                "longitude" to currentLongitude,
                "address" to currentAddress
            )
            methodChannel.invokeMethod("onLocationChanged", locationData)
            
        } catch (e: Exception) {
            Log.e(TAG, "💥 处理选中位置异常: ${e.message}", e)
        }
    }

    /**
     * 逆地理编码
     */
    private fun reverseGeocode(latLng: LatLng) {
        try {
            val geocodeSearch = GeocodeSearch(mapView.context)
            geocodeSearch.setOnGeocodeSearchListener(object : GeocodeSearch.OnGeocodeSearchListener {
                override fun onRegeocodeSearched(result: RegeocodeResult?, rCode: Int) {
                    if (rCode == 1000 && result != null) {
                        val address = result.regeocodeAddress?.formatAddress ?: "地址解析失败"
                        currentAddress = address
                        Log.d(TAG, "📍 地址解析成功: $address")
                        
                        // 通知Flutter端地址更新
                        val addressData = mapOf(
                            "latitude" to currentLatitude,
                            "longitude" to currentLongitude,
                            "address" to currentAddress
                        )
                        methodChannel.invokeMethod("onAddressChanged", addressData)
                    } else {
                        Log.e(TAG, "❌ 地址解析失败, rCode: $rCode")
                    }
                }

                override fun onGeocodeSearched(result: GeocodeResult?, rCode: Int) {
                    // 正向地理编码回调，暂不需要
                }
            })

            val query = RegeocodeQuery(
                LatLonPoint(latLng.latitude, latLng.longitude),
                100f,
                GeocodeSearch.AMAP
            )
            geocodeSearch.getFromLocationAsyn(query)
            
        } catch (e: Exception) {
            Log.e(TAG, "💥 逆地理编码异常: ${e.message}", e)
            currentAddress = "地址获取失败"
        }
    }

    // ====================== PlatformView 接口实现 ======================

    override fun getView(): View = mapView

    override fun dispose() {
        val disposeStartTime = System.currentTimeMillis()
        Log.d(TAG, "🗑️ =============== AmapFlutterMapView.dispose 开始 ===============")
        Log.d(TAG, "⏰ 销毁开始时间戳: $disposeStartTime")
        Log.d(TAG, "🔍 [Thread] 当前线程: ${Thread.currentThread().name}, ID: ${Thread.currentThread().id}")
        Log.d(TAG, "🔍 [View] mapView状态: alpha=${mapView.alpha}, visibility=${mapView.visibility}")
        Log.d(TAG, "🔍 [View] mapView parent: ${mapView.parent}")
        Log.d(TAG, "🔍 [View] mapView windowToken: ${mapView.windowToken}")
        
        try {
            // 🔥 第1步：先暂停地图渲染，避免渲染冲突
            val step1Time = System.currentTimeMillis()
            Log.d(TAG, "🛑 [OpenGL] 第1步：暂停地图渲染 (时间戳: $step1Time)")
            try {
                mapView.onPause()
                val pauseTime = System.currentTimeMillis()
                Log.d(TAG, "✅ [OpenGL] 地图已暂停 (耗时: ${pauseTime - step1Time}ms)")
                
                // 不再等待，prepareDispose中已经等待过了（20ms）
                Log.d(TAG, "✅ [OpenGL] 跳过额外等待，prepareDispose中已等待")
            } catch (e: Exception) {
                Log.e(TAG, "💥 [OpenGL] 暂停地图异常: ${e.message}")
                Log.e(TAG, "💥 [OpenGL] 异常堆栈: ${e.stackTraceToString()}")
            }
            
            // 🔥 第2步：停止定位客户端
            val step2Time = System.currentTimeMillis()
            Log.d(TAG, "🛑 第2步：停止定位客户端 (时间戳: $step2Time)")
            try {
                mLocationClient?.let { client ->
                    Log.d(TAG, "   - 停止定位...")
                    client.stopLocation()
                    Log.d(TAG, "   - 销毁定位客户端...")
                    client.onDestroy()
                    val step2EndTime = System.currentTimeMillis()
                    Log.d(TAG, "✅ 定位客户端已销毁 (耗时: ${step2EndTime - step2Time}ms)")
                }
                mLocationClient = null
            } catch (e: Exception) {
                Log.e(TAG, "💥 停止定位异常: ${e.message}")
            }
            
            // 🔥 第3步：清理POI搜索资源
            val step3Time = System.currentTimeMillis()
            Log.d(TAG, "🛑 第3步：清理POI搜索资源 (时间戳: $step3Time)")
            try {
                poiSearch = null
                val step3EndTime = System.currentTimeMillis()
                Log.d(TAG, "✅ POI搜索资源已清理 (耗时: ${step3EndTime - step3Time}ms)")
            } catch (e: Exception) {
                Log.e(TAG, "💥 清理POI搜索异常: ${e.message}")
            }
            
            // 🔥 第4步：清理地图资源
            val step4Time = System.currentTimeMillis()
            Log.d(TAG, "🛑 [OpenGL] 第4步：清理地图资源 (时间戳: $step4Time)")
            try {
                aMap?.let { map ->
                    Log.d(TAG, "   - 清空地图覆盖物...")
                    map.clear()
                    Log.d(TAG, "✅ [OpenGL] 地图覆盖物已清空")
                }
                aMap = null
                marker = null
                val step4EndTime = System.currentTimeMillis()
                Log.d(TAG, "✅ [OpenGL] 地图资源已清理 (耗时: ${step4EndTime - step4Time}ms)")
            } catch (e: Exception) {
                Log.e(TAG, "💥 [OpenGL] 清理地图资源异常: ${e.message}")
            }
            
            // 🔥 第5步：销毁地图视图（最重要！）
            val step5Time = System.currentTimeMillis()
            Log.d(TAG, "🛑 [OpenGL] 第5步：销毁地图视图 (时间戳: $step5Time)")
            try {
                Log.d(TAG, "   - 调用 mapView.onDestroy()...")
                Log.d(TAG, "🔍 [OpenGL] 销毁前 - mapView状态: alpha=${mapView.alpha}, visibility=${mapView.visibility}")
                
                mapView.onDestroy()
                
                val step5EndTime = System.currentTimeMillis()
                Log.d(TAG, "✅ [OpenGL] 地图视图已销毁 (耗时: ${step5EndTime - step5Time}ms)")
            } catch (e: Exception) {
                Log.e(TAG, "💥 [OpenGL] 销毁地图视图异常: ${e.message}")
                Log.e(TAG, "💥 [OpenGL] 异常堆栈: ${e.stackTraceToString()}")
            }
            
            val disposeEndTime = System.currentTimeMillis()
            val totalTime = disposeEndTime - disposeStartTime
            Log.d(TAG, "⏰ 销毁总耗时: ${totalTime}ms")
            Log.d(TAG, "⏰ 结束时间戳: $disposeEndTime")
            Log.d(TAG, "✅ AmapFlutterMapView 销毁完成")
            Log.d(TAG, "🏁 =============== AmapFlutterMapView.dispose 结束 ===============")
        } catch (e: Exception) {
            Log.e(TAG, "💥 销毁AmapFlutterMapView异常: ${e.message}", e)
            Log.e(TAG, "💥 异常堆栈: ${e.stackTraceToString()}")
        }
    }

    // ====================== MethodChannel 接口实现 ======================

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        try {
            Log.d(TAG, "📞 收到方法调用: ${call.method}")
            
            when (call.method) {
                "prepareDispose" -> {
                    // 🔥 准备销毁：Flutter层通知即将关闭页面
                    val prepareStartTime = System.currentTimeMillis()
                    Log.d(TAG, "📞 =============== 收到prepareDispose调用 ===============")
                    Log.d(TAG, "📞 开始时间戳: $prepareStartTime")
                    Log.d(TAG, "🔍 [OpenGL] prepareDispose 开始执行")
                    Log.d(TAG, "🔍 [Thread] 当前线程: ${Thread.currentThread().name}, ID: ${Thread.currentThread().id}")
                    
                    try {
                        // 🔥 第0步：停止地图渲染和动画
                        val step0Time = System.currentTimeMillis()
                        Log.d(TAG, "🛑 [OpenGL] 第0步：停止所有地图渲染和动画 (时间戳: $step0Time)")
                        aMap?.let { map ->
                            try {
                                // 停止所有动画
                                map.stopAnimation()
                                val step0EndTime = System.currentTimeMillis()
                                Log.d(TAG, "✅ [OpenGL] 地图动画已停止 (耗时: ${step0EndTime - step0Time}ms)")
                            } catch (e: Exception) {
                                Log.e(TAG, "💥 [OpenGL] 停止动画异常: ${e.message}")
                            }
                        }
                        
                        // 🔥 第1步：先暂停地图渲染（改变顺序，先暂停渲染）
                        val step1Time = System.currentTimeMillis()
                        Log.d(TAG, "🛑 [OpenGL] 第1步：暂停地图渲染 (时间戳: $step1Time)")
                        try {
                            mapView.onPause()
                            Log.d(TAG, "✅ [OpenGL] 地图已暂停")
                            
                            // 等待渲染线程完全停止（减少等待时间到20ms，加快返回速度）
                            val sleepStartTime = System.currentTimeMillis()
                            Thread.sleep(20)
                            val sleepEndTime = System.currentTimeMillis()
                            Log.d(TAG, "✅ [OpenGL] 已等待20ms让渲染线程停止 (实际耗时: ${sleepEndTime - sleepStartTime}ms)")
                        } catch (e: Exception) {
                            Log.e(TAG, "💥 [OpenGL] 暂停地图异常: ${e.message}")
                        }
                        
                        // 🔥 第2步：清空地图覆盖物
                        val step2Time = System.currentTimeMillis()
                        Log.d(TAG, "🛑 [OpenGL] 第2步：清空地图覆盖物 (时间戳: $step2Time)")
                        try {
                            aMap?.clear()
                            val step2EndTime = System.currentTimeMillis()
                            Log.d(TAG, "✅ [OpenGL] 地图覆盖物已清空 (耗时: ${step2EndTime - step2Time}ms)")
                        } catch (e: Exception) {
                            Log.e(TAG, "💥 [OpenGL] 清空覆盖物异常: ${e.message}")
                        }
                        
                        // 🔥 第3步：隐藏地图视图（最后隐藏）
                        val step3Time = System.currentTimeMillis()
                        Log.d(TAG, "🛑 [OpenGL] 第3步：隐藏地图视图 (时间戳: $step3Time)")
                        try {
                            // 先设置透明度为0，避免闪烁
                            mapView.alpha = 0f
                            Log.d(TAG, "✅ [OpenGL] 地图视图透明度设为0")
                            
                            // 再设置不可见
                            mapView.visibility = android.view.View.GONE
                            val step3EndTime = System.currentTimeMillis()
                            Log.d(TAG, "✅ [OpenGL] 地图视图已隐藏（GONE）(耗时: ${step3EndTime - step3Time}ms)")
                        } catch (e: Exception) {
                            Log.e(TAG, "💥 [OpenGL] 隐藏视图异常: ${e.message}")
                        }
                        
                        val prepareEndTime = System.currentTimeMillis()
                        result.success(true)
                        Log.d(TAG, "✅ [OpenGL] prepareDispose 完成 (总耗时: ${prepareEndTime - prepareStartTime}ms)")
                        Log.d(TAG, "🏁 =============== prepareDispose 执行结束 ===============")
                    } catch (e: Exception) {
                        Log.e(TAG, "💥 [OpenGL] prepareDispose异常: ${e.message}")
                        Log.e(TAG, "💥 [OpenGL] 异常堆栈: ${e.stackTraceToString()}")
                        // 即使异常也返回成功，因为我们尽力了
                        result.success(false)
                    }
                }
                "moveToLocation" -> {
                    val latitude = call.argument<Double>("latitude")
                    val longitude = call.argument<Double>("longitude")
                    
                    if (latitude != null && longitude != null) {
                        moveToLocation(latitude, longitude)
                        result.success(true)
                    } else {
                        result.error("INVALID_ARGUMENT", "latitude or longitude is null", null)
                    }
                }
                "getCurrentLocation" -> {
                    val locationData = mapOf(
                        "latitude" to currentLatitude,
                        "longitude" to currentLongitude,
                        "address" to currentAddress
                    )
                    result.success(locationData)
                }
                "startLocationSelf" -> {
                    startLocationSelf()
                    result.success(true)
                }
                "searchPOI" -> {
                    Log.d(TAG, "🔍 处理searchPOI方法调用...")
                    val keyword = call.argument<String>("keyword")
                    val city = call.argument<String>("city")
                    
                    Log.d(TAG, "🔍 searchPOI参数: keyword=$keyword, city=$city")
                    
                    if (keyword != null && keyword.isNotEmpty()) {
                        try {
                            searchPOI(keyword, city ?: "")
                            result.success(true)
                            Log.d(TAG, "✅ searchPOI调用成功")
                        } catch (e: Exception) {
                            Log.e(TAG, "💥 searchPOI调用异常: ${e.message}", e)
                            result.error("SEARCH_ERROR", "POI搜索异常: ${e.message}", e.stackTraceToString())
                        }
                    } else {
                        Log.e(TAG, "❌ searchPOI参数无效: keyword=$keyword")
                        result.error("INVALID_ARGUMENT", "keyword is null or empty", null)
                    }
                }
                else -> {
                    result.notImplemented()
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "💥 处理方法调用异常: ${e.message}", e)
            result.error("UNKNOWN_ERROR", e.message, null)
        }
    }

    // ====================== 地图操作方法 ======================

    /**
     * 移动到指定位置
     */
    private fun moveToLocation(latitude: Double, longitude: Double) {
        try {
            val latLng = LatLng(latitude, longitude)
            aMap?.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15f))
            marker?.position = latLng
            
            currentLatitude = latitude
            currentLongitude = longitude
            
            // 更新地址信息
            reverseGeocode(latLng)
            
            Log.d(TAG, "📍 地图已移动到: $latitude, $longitude")
        } catch (e: Exception) {
            Log.e(TAG, "💥 移动地图异常: ${e.message}", e)
        }
    }

    /**
     * 开始定位
     */
    private fun startLocationSelf() {
        try {
            // 标记这是主动触发的定位
            isLocationTriggered = true
            
            if (mLocationClient == null) {
                mLocationClient = AMapLocationClient(mapView.context)
                val locationOption = AMapLocationClientOption().apply {
                    locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
                    isOnceLocation = true
                }
                
                mLocationClient?.setLocationOption(locationOption)
                mLocationClient?.setLocationListener(this)
            }
            
            mLocationClient?.startLocation()
            Log.d(TAG, "🎯 开始定位...")
            
        } catch (e: Exception) {
            Log.e(TAG, "💥 开始定位异常: ${e.message}", e)
            isLocationTriggered = false  // 重置标记
        }
    }

    // ====================== 地图事件监听 ======================

    override fun onMapClick(latLng: LatLng?) {
        latLng?.let { position ->
            Log.d(TAG, "🖱️ 地图点击: ${position.latitude}, ${position.longitude}")
            
            // 更新标记位置
            marker?.position = position
            handleSelectedLocation(position)
        }
    }

    override fun onCameraChange(cameraPosition: CameraPosition?) {
        // 地图移动过程中的回调
    }

    // 防止频繁更新的标志
    private var isUserDragging = false
    private var lastUpdateTime = 0L
    private var isLocationTriggered = false  // 标记是否是主动触发的定位
    
    override fun onCameraChangeFinish(cameraPosition: CameraPosition?) {
        // 地图移动结束的回调，但避免频繁自动跳转
        cameraPosition?.target?.let { target ->
            Log.d(TAG, "📹 地图移动结束: ${target.latitude}, ${target.longitude}")
            
            // 防止频繁更新，只有超过1秒才处理
            val currentTime = System.currentTimeMillis()
            if (currentTime - lastUpdateTime < 1000) {
                Log.d(TAG, "⏰ 跳过频繁更新")
                return
            }
            lastUpdateTime = currentTime
            
            // 更新标记位置，但不移动地图
            marker?.position = target
            handleSelectedLocation(target, false) // 传入false表示不要移动地图
        }
    }

    // ====================== 定位相关方法 ======================

    override fun onLocationChanged(location: AMapLocation?) {
        location?.let { loc ->
            if (loc.errorCode == 0) {
                Log.d(TAG, "📍 定位成功: ${loc.latitude}, ${loc.longitude}")
                
                // 更新当前位置
                currentLatitude = loc.latitude
                currentLongitude = loc.longitude
                currentAddress = loc.address ?: "位置信息获取中..."
                
                // 只有在主动触发定位时才移动地图，避免用户拖拽时自动跳转
                if (isLocationTriggered) {
                    Log.d(TAG, "🎯 主动定位，移动地图到新位置")
                    val latLng = LatLng(currentLatitude, currentLongitude)
                    aMap?.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15f))
                    marker?.position = latLng
                    
                    // 重置触发标记
                    isLocationTriggered = false
                } else {
                    Log.d(TAG, "🚫 被动定位，不移动地图")
                }
                
                // 通知Flutter端
                val locationData = mapOf(
                    "latitude" to currentLatitude,
                    "longitude" to currentLongitude,
                    "address" to currentAddress
                )
                methodChannel.invokeMethod("onLocationSuccess", locationData)
            } else {
                Log.e(TAG, "❌ 定位失败: ${loc.errorCode}, ${loc.errorInfo}")
                methodChannel.invokeMethod("onLocationError", loc.errorInfo ?: "定位失败")
                isLocationTriggered = false  // 重置标记
            }
        }
    }

    // ====================== POI搜索功能 ======================

    /**
     * 执行POI搜索
     */
    private fun searchPOI(keyword: String, city: String) {
        try {
            Log.d(TAG, "🔍 开始POI搜索: keyword=$keyword, city=$city")
            
            val query = PoiSearch.Query(keyword, "", city)
            query.pageSize = 10  // 每页10个结果
            query.pageNum = 1    // 第一页
            
            poiSearch = PoiSearch(mapView.context, query)
            poiSearch?.setOnPoiSearchListener(this)
            poiSearch?.searchPOIAsyn()
            
            Log.d(TAG, "🔍 POI搜索请求已发送")
        } catch (e: Exception) {
            Log.e(TAG, "💥 POI搜索异常: ${e.message}", e)
            // 通知Flutter端搜索失败
            methodChannel.invokeMethod("onSearchError", "搜索失败: ${e.message}")
        }
    }
    
    /**
     * POI搜索结果回调
     */
    override fun onPoiSearched(result: PoiResult?, code: Int) {
        Log.d(TAG, "📋 收到POI搜索结果: code=$code")
        
        if (code == 1000 && result != null) {
            val poiList = result.pois
            if (poiList.isNotEmpty()) {
                Log.d(TAG, "✅ 搜索成功，找到${poiList.size}个结果")
                
                // 将POI结果转换为Flutter能理解的数据格式
                val searchResults = poiList.map { poi ->
                    mapOf(
                        "title" to poi.title,
                        "snippet" to poi.snippet,
                        "latitude" to poi.latLonPoint.latitude,
                        "longitude" to poi.latLonPoint.longitude,
                        "cityName" to poi.cityName,
                        "adName" to poi.adName,
                        "distance" to poi.distance
                    )
                }
                
                // 通知Flutter端搜索成功
                methodChannel.invokeMethod("onSearchSuccess", searchResults)
                
                Log.d(TAG, "📤 已发送${searchResults.size}个搜索结果到Flutter")
                
            } else {
                Log.d(TAG, "⚠️ 搜索结果为空")
                methodChannel.invokeMethod("onSearchSuccess", emptyList<Map<String, Any>>())
            }
        } else {
            Log.e(TAG, "❌ POI搜索失败，错误码: $code")
            methodChannel.invokeMethod("onSearchError", "搜索失败，错误码: $code")
        }
    }
    
    /**
     * POI详情搜索回调（必须实现的接口方法）
     */
    override fun onPoiItemSearched(poiItem: PoiItem?, code: Int) {
        // 这里暂时不需要实现详情搜索
    }

    // ====================== 生命周期方法 ======================

    fun onResume() {
        mapView.onResume()
    }

    fun onPause() {
        mapView.onPause()
    }

    fun onSaveInstanceState(outState: Bundle?) {
        mapView.onSaveInstanceState(outState)
    }
}
